package com.file;

import java.io.*;
import java.util.ArrayList;

/**
 * Created by TimeLiar on 2015/9/17.
 * All Hail The King !!!!!!
 */
public enum FileManager {
    @SuppressWarnings("unused")
    INSTANCE;
    private static BufferedReader reader;

    /**
     * read
     */
    public static String readFile(String path) throws IOException {
        File file = new File(path);
        if (!file.exists() || !file.isFile()) {
            return null;
        }
        reader = new BufferedReader(new FileReader(file));
        String tmp;
        StringBuilder builder = new StringBuilder();
        while ((tmp = reader.readLine()) != null) {
            builder.append(tmp);
        }
        reader.close();
        return builder.toString();
    }

    public static void writeFile(Object object, String target, boolean append) throws IOException {
        BufferedWriter writer = new BufferedWriter(new FileWriter(new File(target), append));
        writer.write(object.toString());
        writer.flush();
        writer.close();
    }

    @SuppressWarnings("unused")
    public static ArrayList<String> readLines(String path) throws IOException{
        ArrayList<String> strings = new ArrayList<>();
        File file = new File(path);
        if (!file.exists() || !file.isFile()) {
            return null;
        }
        reader = new BufferedReader(new FileReader(file));
        String tmp;
        while ((tmp = reader.readLine()) != null) {
            strings.add(tmp);
        }
        reader.close();
        return strings;
    }

    public static Object readObject(String path) throws IOException, ClassNotFoundException {
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(path));
        Object object = objectInputStream.readObject();
        objectInputStream.close();
        return object;
    }

    public static void writeObject(Object object , String path) throws IOException {
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(path));
        objectOutputStream.writeObject(object);
        objectOutputStream.flush();
        objectOutputStream.close();
    }
}
